package middleware

import (
	"strings"
	"time"

	"gitee.com/botaoshow/yuanxin/web/common/redis"
	"gitee.com/botaoshow/yuanxin/web/response"
	"gitee.com/botaoshow/yuanxin/web/utils/tokens"

	"github.com/gin-gonic/gin"
)

const (
	TokenHeaderKey = "Authorization"
	TokenPrefix    = "Bearer "
)

// JwtRedisAuthHandler 定义JWT身份验证中间件
func JwtRedisAuthHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader(TokenHeaderKey)
		if tokenString == "" || len(tokenString) == 0 || tokenString == TokenPrefix {
			response.Resp(c, response.CodeUnauthorized, "未登录认证！", nil)
			c.Abort()
			return
		}

		//判断Bearer 开头
		if strings.HasPrefix(tokenString, TokenPrefix) {
			tokenString = tokenString[7:]
		}

		claims, err := tokens.ParseToken(tokenString)
		if err != nil {
			response.Resp(c, response.CodeUnauthorized, "未登录认证！"+err.Error(), nil)
			c.Abort()
			return
		}
		//【扩展】根据短token查询redis
		//判断是否过期
		result, _ := redis.Rdb.Exists(c, claims.ShortToken).Result()
		if result == 0 {
			response.Resp(c, response.CodeUnauthorized, "认证信息已过期，请重新登录认证！", nil)
			c.Abort()
			return
		}
		duration, err := redis.Rdb.TTL(c, claims.ShortToken).Result()
		//是否需要续签；
		if duration < 120*time.Second {
			// 续期
			redis.Rdb.Expire(c, claims.ShortToken, time.Hour*48)
		}
		// 继续处理请求
		c.Next()
	}
}
